<template>
	<view>
		<view class="account-top">
			<image class="headPhoto" mode="aspectFit" src="../../static/headPhoto.png"></image>
			<view class="account-name">{{username}}</view>
		</view>
		<view class="task">
			<view class="task-tip">请按照标准进行数据填写！</view>
			<view class="task-header" @click="toggleTaskContent">
				<view class="task-name">
					<view style="width: 90%;">{{this.inspectionData.inspectionDataName}}</view>
					<uni-icons v-if="isTaskContentVisible" type="up" class="arrow-icon" size="30"></uni-icons>
					<uni-icons v-else type="down" class="arrow-icon" size="30"></uni-icons>
				</view>
				<view class="task-details-wrapper" :class="{ 'expanded': isTaskContentVisible }">
					<view class="task-details">
						<view class="task-item">检查项目：{{this.inspectionData.inspectionDataDesc}}</view>
						<view class="task-item">
							<view>任务状态：</view>
							<view>
								<view style="color: #4CAF50;" v-if="this.inspectionData.inspectionDetailStatus === 0">处理中</view>
								<view style="color: red;" v-else-if="this.inspectionData.inspectionDetailStatus === 1">已超时</view>
								<view style="color: #0A60BD;" v-else-if="this.inspectionData.inspectionDetailStatus === 2">已完成</view>
								<view style="color: grey;" v-else-if="this.inspectionData.inspectionDetailStatus === 3">已取消</view>
								<view style="color: red;" v-else-if="this.inspectionData.inspectionDetailStatus === 4">异常</view>
								<view style="color: grey;" v-else-if="this.inspectionData.inspectionDetailStatus === 6">未开始</view>
								<view v-else>其他状态</view>
							</view>
						    
						</view>
						<view class="task-item">任务机组：{{this.inspectionData.unitName}}</view>
						<view class="task-item">任务班组：{{this.inspectionData.inspectionDetailClass}}</view>
						<view class="task-item">任务点位号：{{this.inspectionData.mapDetailId}}</view>
						<view class="task-item">任务点位描述：{{this.inspectionData.mapDetailDesc}}</view>
						<view class="task-item">任务巡检员：{{this.inspectionData.inspectionDetailUser}}</view>
					</view>
				</view>
			</view>
			<view class="task-body">
				<view class='data-title'></view>
				<view v-for="(group, index) in inspectionGroups" :key="index" class="task-content">
					<view class="task-left">{{ group.attribute }}</view>
					<view class="task-right">
						<input type="text" v-model="group.value" placeholder="请输入数据" class="task-input" />
						<span>{{ group.perUnit }}</span>
					</view>
				</view>
				<view class="normalContent">
					<view style="font-size: 20px;">数据是否异常</view>
					<radio-group value="isAbnormal" @change="onAbnormalChange" class="normalSelect">
						<radio :value="true" class="radio-item">异常</radio>
						<radio :value="false" class="radio-item">正常</radio>
					</radio-group>
					<view v-if="isAbnormal">
						<view style="font-size: 18px;">问题描述：</view>
						<textarea class="msgInput" placeholder="请输入异常描述" v-model="this.abnormalMsg"></textarea>
					</view>
				</view>
				<view class="photos">
					<view class="photo-box">
						<view class="photo" v-for="(item,index) in list">
							<image :src="item" class="photo" mode="aspectFill" @tap="checkPhoto(item)" draggable />
							<view @click.stop="delImage(index)" style="display: inline;" class="delPhoto">
								<uni-icons type="closeempty" class="close" size="20"></uni-icons>
							</view>
						</view>


						<view v-show="this.photoCount < 9" class="camera-section">
							<view class="camera-box" @click="takePhoto">
								<uni-icons type="camera" size="30"></uni-icons>
								<view class="camera-text">点击拍摄图片</view>
							</view>
						</view>
					</view>
					<!-- 带相机图标的拍摄图片组件 -->
				</view>
			</view>
			<button type="primary" style="width: 90%;border-radius: 20px;margin: 20px;" @tap="submitData">提交</button>
			<view style="height: 10px;"></view>
		</view>
	</view>
</template>

<script>
	import request from '../../common/request';
	import {
		getJsonData,
		changeData,
		CreateNewDir,
		saveFile
	} from '@/common/file.js'
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	export default {
		data() {
			return {
				username: "苏建宁",
				isTaskContentVisible: false,
				inspectionData: {},
				inspectionGroups: [],
				savedPhotoPath: '', // 存储保存后的图片路径
				list: [], //图片列表
				showPhoto: false,
				photoCount: 0,
				photoSrc: "",
				formData: [],
				noVal: true,
				voicePath: '',
				Name: "",
				isAbnormal: null,
				abnormalMsg: "",
			};
		},
		onLoad(options) {
			this.inspectionData = JSON.parse(decodeURIComponent(options.inspectionData));
			this.getGroup()

			this.startRecord()
		},
		// 离开当前页面
		onBackPress(options) {
			// 判断表单项是否有输入过值
			// const noVal = Object.values(this.formData).some((item) => item);

			// 如果有输入过值，在离开当前页面时提示
			// if (this.noVal) {
			if (0==1) {
				uni.showModal({
					title: "提示",
					content: "信息未保存，是否退出？",
					success: (res) => {
						if (res.confirm) {
							//清理数据
							this.noVal = false
							uni.navigateBack()
						}
					},
				});
				// return true 不会执行默认返回，也就是不会离开当前页
				return true;
			} else {
				// return false 表示执行默认返回
				return false;
			}
		},
		methods: {
			onAbnormalChange(event) {
				this.isAbnormal = event.detail.value
				console.log(event.detail.value)
			},
			//获取当前时间
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 5;
				} else if (type === 'end') {
					year = year;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			//录音功能
			startRecord() {
				const voiceFile = ""
				console.log('开始录音');
				recorderManager.start({
					duration: 20000 // 录音时长 20 秒
				});

				// 设置录音结束监听
				recorderManager.onStop((res) => {
					console.log('录音结束', res);
					this.voicePath = res.tempFilePath; // 获取录音文件路径
					console.log('录音文件路径：', this.voicePath);
					// voiceFile = res.tempFilePath
					this.saveVoiceFile(this.voicePath)
				});

			},
			saveVoiceFile(voiceFile) {
				// 生成新的文件名
				const newFileName = `${this.Name}.mp3`; // 根据需求更改扩展名

				saveFile(`_doc/uniapp_save/${this.Name}`, voiceFile, newFileName)
				// uni.saveFile({
				// 	tempFilePath: voiceFile,
				// 	// filePath: `${uni.env.DOCUMENT_ROOT}/${newFileName}`,
				// 		success: (saveFileRes) => {

				// 			console.log('音频保存成功:');
				// 		},
				// 		fail: (err) => {
				// 			console.error('保存失败:', err);
				// 		}
				// })
			},
			toggleTaskContent() {
				this.isTaskContentVisible = !this.isTaskContentVisible;
			},
			takePhoto() {
				uni.chooseImage({
					count: 9,
					sizeType: ['original', 'compressed'],
					sourceType: ['camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						this.showPhoto = true

						// 生成新的文件名
						const newFileName = `${(this.photoCount+1)*10000+this.Name}.jpg`; // 根据需求更改扩展名

						// 保存文件到本地存储
						saveFile(`_doc/uniapp_save/${this.Name}`, tempFilePath, newFileName)
						this.list.push(res.tempFilePaths[0])
						this.photoSrc = tempFilePath
						this.photoCount++
						// uni.saveFile({
						// 	tempFilePath,
						// 	// filePath: `${uni.env.DOCUMENT_ROOT}/${newFileName}`,
						// 	success: (saveFileRes) => {
						// 		// 成功保存后，保存路径到 list，用于显示图片
						// 		this.list.push(res.tempFilePaths[0])
						// 		this.photoSrc = tempFilePath
						// 		this.photoCount++
						// 		console.log('照片保存成功:', this.list);
						// 	},
						// 	fail: (err) => {
						// 		console.error('保存失败:', err);
						// 	}
						// });
					},
					fail: (err) => {
						console.error('拍摄失败:', err);
					}
				});
			},
			checkPhoto(item) {
				//查看图片
				console.log("图片路径为：" + item)
				uni.previewImage({
					current: item,
					urls: [this.photoSrc]
				})
			},
			//删除
			delImage: async function(index) {
				uni.showModal({
					title: '删除照片',
					content: '确定要删除这张照片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						console.log(res)
						if (res.confirm) {
							this.list.splice(index, 1)
							this.photoCount--
						}
					}
				})
				const delName = `${(index+1)*10000+this.Name}+jpg`
				uni.removeSavedFile({
					filePath: `_doc/uniapp_save/${this.Name}/${delName}`,
					success() {
						console.log("删除成功")
					}
				})
			},
			getGroup() {
				request(`/inspection/data/${this.inspectionData.inspectionGroupId}`).then(res => {
					console.log("getGroup")
					console.log(res)
					console.log(this.inspectionData.inspectionGroupId+" "+this.inspectionData.inspectionDetailId)
					this.Name = String(this.inspectionData.inspectionGroupId * 100 + this.inspectionData.inspectionDetailId)
					console.log(this.Name)
					this.inspectionGroups = res.data.data
				})
			},
			toData() {
				CreateNewDir('_doc/uniapp_save', this.Name)
				const dataToWrite = {
					text: this.inspectionGroups,
					abnormal: this.isAbnormal,
					abnormalMsg: this.isAbnormal ? this.abnormalMsg : ""
				}
				const jsonString = JSON.stringify(dataToWrite);
				//兼容安卓10+ （通用）
				const pathUrl = plus.io.convertLocalFileSystemURL("_downloads/") + this.Name + '.json'
				//安卓10以下路径地址  
				const pathUrl2 = '/storage/emulated/0/' + this.Name + '.json'
				//安卓10+	pathUrl2  会报targetSdkVersion设置>=29后在Android10+系统设备不支持当前路径。请更改为应用运行路径


				changeData(pathUrl, 0, jsonString);
				saveFile(`_doc/uniapp_save/${this.Name}`, pathUrl, this.Name + '.json')
			},
			normalSubmit() {
				if (this.isAbnormal === false) {
					this.abnormalMsg = ""
				}
				console.log("输出异常信息")
				console.log(this.abnormalMsg)
				if (this.isAbnormal === true && this.abnormalMsg === "") {
					uni.showToast({
						title: "请填入异常描述信息",
						icon: 'none',
					})
				} else if (this.isAbnormal === null) {
					uni.showToast({
						title: "请确认数据是否异常",
						icon: 'none',
					})
				} else {
					uni.showModal({
						content: "是否提交已填数据?",
						success: (res) => {
							if (res.confirm) {
								//提交数据
								this.toData()
								this.noVal = true
								uni.showToast({
									title: "提交成功,正在返回任务列表...",
									icon: 'none'
								})
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
							}
						}
					})

					this.isAbnormal = null
					this.abnormalMsg = ""
				}

			},
			noNormalSubmit() {
				this.isAbnormal = null
				this.abnormalMsg = ""
			},
			submitData() {
				this.noVal = false
				for (let i = 0; i < this.inspectionGroups.length; i++) {
					if (!this.inspectionGroups[i].value) {
						this.noVal = true
					}
				}
				if (this.noVal === false) {
					if(this.isAbnormal === null){
						uni.showToast({
							title:"请确定数据是否异常",
							icon:'none'
						})
					}else{
						this.normalSubmit()
					}
				} else {
					uni.showToast({
						title: "请将数据填充完整",
						icon: 'none',
					})
				}

			},
			// 连接到指定蓝牙设备
			// connectBluetooth(address) {
			//   BluetoothClassic.connectToDevice({
			//     address: address
			//   }, (res) => {
			//     if (res.status === 'success') {
			//       console.log('连接成功');
			//     } else {
			//       console.error('连接失败');
			//     }
			//   });
			// },

			// 发送文件到连接的设备
			// sendFileToBluetooth(filePath) {
			//   BluetoothClassic.sendFile({
			//     filePath: filePath
			//   }, (res) => {
			//     if (res.status === 'success') {
			//       console.log('文件发送成功');
			//     } else {
			//       console.error('文件发送失败');
			//     }
			//   });
			// },

			// 断开蓝牙连接
			// disconnectBluetooth() {
			//   BluetoothClassic.disconnect({}, (res) => {
			//     if (res.status === 'success') {
			//       console.log('断开连接成功');
			//     } else {
			//       console.error('断开连接失败');
			//     }
			//   });
			// },
		}
	}
</script>

<style scoped>
	.account-top {
		background-color: white;
		height: 80px;
		display: flex;
		align-items: center;
		padding-left: 20px;
	}

	.headPhoto {
		width: 60px;
		height: 60px;
		margin-right: 20px;
	}

	.account-name {
		width: 50%;
		font-size: 30px;
	}

	.task-header {
		background-color: #fff;
		padding: 20px;
		margin: 10px;
		border-radius: 20px;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.15);
		cursor: pointer;
		transition: all 0.5s ease;
	}

	.task-details-wrapper {
		overflow: hidden;
		transition: max-height 0.5s ease;
		max-height: 50px;
	}

	.task-details-wrapper.expanded {
		max-height: 500px;
	}

	.task-details {
		margin-top: 20px;
		font-size: 18px;
	}

	.task-item {
		margin-bottom: 10px;
		display: flex;
	}

	.task-tip {
		padding: 20px;
	}

	.task-name {
		font-size: 25px;
	}

	.task-body {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.task-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20px;
		background-color: #fff;
		margin: 10px;
		border-radius: 20px;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.15);
	}

	.task-left {
		flex: 1;
		margin-right: 5px;
	}

	.task-right {
		font-size: 20px;
		color: #4CAF50;
		display: flex;
		align-items: center;
	}

	.camera-section {
		width: 180rpx;
		height: 250rpx;
		text-align: center;
		padding: 5px;
	}

	.photo-box {
		width: 100%;
		height: 180rpx;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		margin-bottom: 20px;
	}

	.photo {
		width: 180rpx;
		height: 180rpx;
		margin: 3px;
		position: relative;
	}

	.camera-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #f2f2f2;
		border: 2px dashed #ccc;
		border-radius: 10px;
		cursor: pointer;
		transition: background-color 0.3s ease;
		width: 180rpx;
		height: 180rpx;
	}

	.camera-box:hover {
		background-color: #e6e6e6;
	}

	.camera-icon {
		font-size: 50px;
		color: #888;
	}

	.camera-text {
		margin-top: 10px;
		font-size: 16px;
		color: #888;
	}

	.captured-photo {
		margin-top: 10px;
		width: 100%;
		height: auto;
		border-radius: 5px;
	}

	.arrow-icon {
		float: right;
		font-size: 30px;
		/* 		transform: translateY(10px); */
	}

	.photos {
		width: 80%;
	}

	.delPhoto {
		right: -2px;
		top: 3px;
		z-index: 999;

		/* 		overflow: auto; */
		position: absolute;
	}

	.close {
		/* 		position: absolute; */
		right: 0px;
		top: 0px;
		border-radius: 10px;
		width: 10px;
		height: 10px;
		background-color: rgba(220, 220, 220, 0.5);
	}

	.normalConfirm {
		width: 80%;
		max-height: 40%;
		background-color: #fff;
		position: fixed;
		left: 10%;
		top: 30%;
		z-index: 2;
		display: flex;
		flex-direction: column;
		align-items: center;
		border-radius: 20px;
		padding-bottom: 30px;
	}

	.darkBackground {
		background-color: rgba(0, 0, 0, 0.5);
		/* 设置暗色背景 */
		position: fixed;
		/* 使背景覆盖整个视口 */
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
		/* 确保在其他元素之上 */
	}

	.normalContent {
		margin-top: 20px;
		background-color: #fff;
		align-self: center;
		justify-self: center;
		padding: 10px;
		width: 80%;
		border-radius: 20px;
		display: flex;
		flex-direction: column;
		/* 		background-color: red; */
	}

	.normalSelect {
		margin-top: 10px;
		padding: 10px;
		display: flex;
		padding-bottom: 20px;
	}

	.radio-item {
		flex: 50%;
	}

	.msgInput {
		margin-top: 10px;
		background-color: #f8f8f8;
		min-height: 20px;
	}

	.submitBtn {
		margin-top: 20px;
		text-align: center;
		max-height: 35px;
		display: flex;
		align-items: center;
	}
	.task-input{
		color: black;
	}
</style>